#include <stdio.h>
#include <string.h>
#include "tcpsrv.h"

int currentdepth = 0;
int elements = 0;
int groupelements =0;
char *squidhome,*squidpid,*squidswapfile,*squidversion;
char *squidgroup[MAX_GROUP]={"","","","","","","","","",""};
char buf[MAX_BUF];
int Conf;

struct queue_table * queue_head;

static void XMLCALL startElement(void *userData,const char *name,const char **attr){
	currentdepth++;
	if (currentdepth==2){
		elements++;
	}
	if (currentdepth==3){
		groupelements++;
	}
}

static void XMLCALL endElement(void *userData,const char *name){
	currentdepth--;	
}

static void chardatahandle(void *userData,const char *s,int len){
	
	unsigned char str[len+1];
	int i;
	for(i=0;i<len;i++){
		str[i]=s[i];
	}
	str[len] = '\0';
	//printf("%s",str);
	//return;
	if (currentdepth == 2){
		if (elements == 1){
			squidhome = strdup(str);			
		}
		else if(elements == 2){
			squidpid = strdup(str);
		}
		else if(elements == 3){
			squidswapfile = strdup(str);
		}
		else if(elements == 5){
			squidversion = strdup(str);
		}
		//printf("%d\n",elements);
		//printf("%.*s\n",len,s);
	}
	else if (currentdepth == 3){
		int j = 0;
		for (j=0;j<MAX_GROUP;j++){
			//printf("strlen %d \n",strlen(squidgroup[j]));
			if (!strlen(squidgroup[j])){
				//printf("%d\n",j);
				squidgroup[j] = strdup(str);
				return;
			}
		}
	}
}

void parsexml()
{
	FILE *fd;
	int done;

	XML_Parser parser = XML_ParserCreate(NULL);

	if (!parser){
		printf ("%s","create XML_Parser error\n");
		return;
	}

	XML_SetElementHandler(parser,startElement,endElement);
	XML_SetUserData(parser,&Conf);
	XML_SetCharacterDataHandler(parser,chardatahandle);	

	fd = fopen("config.xml","r");
	if (!fd){
		printf("%s","Not found config.xml\n");
		XML_ParserFree(parser);
		return;
	}
	
	size_t len = fread(buf,1,MAX_BUF,fd);
	done = len < sizeof(buf);	
	if (!XML_Parse(parser,buf,len,done))
	{
		XML_ParserFree(parser);
		fclose(fd);
		return;
	}
	XML_ParserFree(parser);

	fclose(fd);
	return ;
}
/*
int main(){
	parsexml();
	printf("squidhome: %s\n",squidhome);
	printf("squidpid: %s\n",squidpid);
	printf("squidswapfile: %s\n",squidswapfile);
	printf("squidversion: %s\n",squidversion);
	printf("squidgroup1: %s\n",squidgroup[0]);
	printf("squidgroup2: %s\n",squidgroup[1]);
	//int i = sizeof(struct queue_table);
	//printf ("%s",i);
	return 0;
}
*/
